﻿using Ardalis.Specification;
using Common.Utils;
using Domain.Entities.Loggers;

namespace Application.Features.Monitors.Specifications;

#nullable disable

public class LoggerAdvancedPaginationSpec : Specification<Logger>
{
    public LoggerAdvancedPaginationSpec(LoggerAdvancedFilter filter)
    {

        long? starTime = default;
        long? endTime = default;
        if (filter.StarTime.HasValue && filter.EndTime.HasValue && filter.StarTime < filter.EndTime) //为了兼容sqlite数据库
        {
            starTime = filter.StarTime.Value.ToUnixTimestampMilliseconds();
            endTime = filter.EndTime.Value.ToUnixTimestampMilliseconds();
        }
        if (filter.MessageTemplate == "login")
        {
            Query.Where(q => q.Level != "Debug")
                 .Where(q => q.Message!.StartsWith("\"密码登录\","))
                 .Where(q => q.Message!.StartsWith($"\"密码登录\",\"{filter.UserName}\","), !filter.UserName!.IsNullOrWhiteSpace())
                 .Where(q => q.Level == filter.Level, !filter.Level!.IsNullOrWhiteSpace())
                 .Where(q => q.Message.EndsWith(filter.StatusCode), !filter.StatusCode.IsNullOrWhiteSpace())
                 .Where(q => q.TimestampLong >= starTime && q.TimestampLong <= endTime, starTime.HasValue && endTime.HasValue);
        }
        else if (filter.MessageTemplate == "operation")
        {
            Query.Where(q => q.Level != "Debug")
                 .Where(q => q.Message!.Contains($",\"{filter.Keyword}\","), !filter.Keyword!.IsNullOrWhiteSpace())
                 .Where(q => q.Message!.StartsWith("\"操作日志\","))
                 .Where(q => q.Message!.StartsWith($"\"操作日志\",\"{filter.UserName}\","), !filter.UserName!.IsNullOrWhiteSpace())
                 .Where(q => q.Level == filter.Level, !filter.Level!.IsNullOrWhiteSpace())
                 .Where(q => q.TimestampLong >= starTime && q.TimestampLong <= endTime, starTime.HasValue && endTime.HasValue);
        }
        else 
        {
            Query.Where(q => q.Level != "Debug")
                 .Where(q => q.Message!.Contains($",\"{filter.Keyword}\","), !filter.Keyword!.IsNullOrWhiteSpace())
                 .Where(q => q.Level == filter.Level, !filter.Level!.IsNullOrWhiteSpace())
                 .Where(q => q.Message!.StartsWith($"\"密码登录\",\"{filter.UserName}\",") || q.Message!.StartsWith($"\"操作日志\",\"{filter.UserName}\","), !filter.UserName!.IsNullOrWhiteSpace())
                 .Where(q => q.TimestampLong >= starTime && q.TimestampLong <= endTime, starTime.HasValue && endTime.HasValue);
        }
    }
}